package cn.yzj.openapi.utils;

import cn.yzj.openapi.enums.error.SettingsErrorEnums;
import cn.yzj.openapi.exception.OpenApiException;
import cn.yzj.utils.JsonUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * 配置JSON工具类
 *
 * @author gzkemays
 * @since 10/16/2022
 */
public class SettingsJsonUtils {
  JSONObject json = new JSONObject();

  public static SettingsJsonUtils builder() {
    return new SettingsJsonUtils();
  }

  /**
   * 转换 json string
   *
   * @param settings 配置字符串
   * @return json string
   */
  public static String parseJson(String settings) {
    if (!JsonUtils.isJson(settings)) {
      throw OpenApiException.settingsException(SettingsErrorEnums.SETTINGS_IS_NO_JSON);
    }
    return JSON.toJSONString(settings);
  }

  public static String getSettingsVal(String settings, String key) {
    if (settings.contains("\\\"")) {
      int last = settings.lastIndexOf("\"");
      settings = settings.substring(0, last);
      settings = settings.replaceFirst("\"", "").replace("\\\"", "\"");
    }
    return JsonUtils.strJsonGetValueByKey(settings, key);
  }

  public SettingsJsonUtils setSettingsVal(String key, Object val) {
    json.put(key, val);
    return this;
  }

  public String buildSettingsVal() {
    String settings = json.toJSONString();
    if (settings.contains("\\\"")) {
      int last = settings.lastIndexOf("\"");
      settings = settings.substring(0, last);
      settings = settings.replaceFirst("\"", "").replace("\\\"", "\"");
    }
    return settings;
  }

  public static void main(String[] args) {
    System.out.println(
        SettingsJsonUtils.builder().setSettingsVal("picMaxCount", 313).buildSettingsVal());
  }
}
